<template>
    <div>
        <h-section title="用户使用时长统计" collapse>
            <div class="form-cont">
                <flexbox style="font-size: 13px">
                    <span class="margin-r-16">统计方式：</span>
                    <a-select v-model:value="tongjiType" style="width: 200px" class="margin-r-8" @change="handleSelectTongjiTypeChange">
                        <a-select-option key="1">按季度统计</a-select-option>
                        <a-select-option key="2">按年度统计</a-select-option>
                    </a-select>
                    <HYearPickerCell :allowClear="false" v-model:value="selectYear" class="margin-r-16" @change="getRangeDate" />

                    <a-select
                        v-model:value="selectMonthOrQuarter"
                        style="width: 100px"
                        class="margin-r-16"
                        v-if="['1'].includes(tongjiType)"
                        @change="getRangeDate"
                    >
                        <a-select-option v-for="item of timeOptions" :key="item.name" :value="item.value">
                            {{ item.name }}
                        </a-select-option>
                    </a-select>
                </flexbox>

                <a-divider />

                <flexbox>
                    <div :class="['card-item', currIndex === 0 ? 'active-1-bg' : 'border']" @click="handleSelectUserType(0)">
                        <flexbox style="margin-top: 24px; margin-left: 26px">
                            <img style="width: 18px; height: 18px" src="@/assets/images/yonghutongji/user-1.png" />
                            <span style="font-size: 14px" :class="[currIndex === 0 ? 'active-1-text' : '', 'margin-l-8']">活跃用户</span>
                        </flexbox>
                        <span style="position: absolute; top: 24px; right: 68px; font-size: 36px"> {{ huoyueTotal }} </span>
                    </div>
                    <div
                        style="margin-left: 24px"
                        :class="['card-item', currIndex === 1 ? 'active-2-bg' : 'border']"
                        @click="handleSelectUserType(1)"
                    >
                        <flexbox style="margin-top: 24px; margin-left: 26px">
                            <img style="width: 18px; height: 18px" src="@/assets/images/yonghutongji/user-2.png" />
                            <span style="font-size: 14px" :class="[currIndex === 1 ? 'active-2-text' : '', 'margin-l-8']">新增用户</span>
                        </flexbox>
                        <span style="position: absolute; top: 24px; right: 68px; font-size: 36px">{{ addTotal }}</span>
                    </div>
                </flexbox>

                <flexbox justify="space-between" style="font-size: 12px; margin-top: 24px">
                    <flexbox>
                        <span class="margin-l-16 margin-r-16">团队：</span>
                        <h-cascader
                            placeholder="请选择"
                            :options="subTeamOptions"
                            :change-on-select="true"
                            labelField="name"
                            valueField="id"
                            show-search
                            childrenField="subList"
                            @change="handleCascaderChange"
                        ></h-cascader>

                        <a-button class="margin-l-8" @click="handleSubmit">筛选</a-button>
                    </flexbox>
                    <a-button type="primary" class="margin-l-8" @click="exportFile">导出</a-button>
                </flexbox>
            </div>
            <div class="margin-t-16">
                <a-table
                    rowKey="id"
                    size="small"
                    :loading="loading"
                    :columns="tableColumns"
                    :data-source="list"
                    :pagination="paginationConfig"
                    @change="handleTableChange"
                >
                    <template #customMonthTitle1>
                        <span>{{ selectMonthOrQuarter * 3 - 2 }}月</span>
                    </template>
                    <template #customMonthTitle2>
                        <span>{{ selectMonthOrQuarter * 3 - 1 }}月</span>
                    </template>
                    <template #customMonthTitle3>
                        <span>{{ selectMonthOrQuarter * 3 }}月</span>
                    </template>
                    <template #month1="{ record }">
                        {{ record[`month${selectMonthOrQuarter * 3 - 2}`] }}
                    </template>
                    <template #month2="{ record }">
                        {{ record[`month${selectMonthOrQuarter * 3 - 1}`] }}
                    </template>
                    <template #month3="{ record }">
                        {{ record[`month${selectMonthOrQuarter * 3}`] }}
                    </template>
                    <template #customTotalTitle>
                        <span v-if="tongjiType === '1'">{{ `第${selectMonthOrQuarter}季度累积使用时长` }}</span>
                        <span v-else>{{ `${selectYear}年累积使用时长` }}</span>
                    </template>

                    <template #index="{ index }">
                        {{ index + 1 }}
                    </template>
                </a-table>
            </div>
        </h-section>
    </div>
</template>

<script lang="ts">
import { ref, computed, reactive, defineComponent, toRefs } from 'vue';
import api from '@/api';
import moment from 'moment';
import { downByBlob } from '@/utils/file/downFile';
import { useTableLoading, usePagination } from '@/components/Table/hooks';
import { HYearPickerCell, HCascader } from '@/components';
export default defineComponent({
    components: {
        HYearPickerCell,
        HCascader
    },
    setup() {
        const tongjiType = ref<string>('1');
        const selectYear = ref<any>(moment().year().toString());
        const currIndex = ref<number>(0);
        const subTeamOptions = ref<any>([]);
        const list = ref<any>([]);
        const huoyueTotal = ref<number>(0);
        const addTotal = ref<number>(0);
        const state = reactive<any>({
            startTime: null,
            endTime: null,
            departmentId: '',
            teamId: ''
        });
        const { loading, setLoading } = useTableLoading();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const timeOptions = computed(() => {
            if (tongjiType.value === '1') {
                return new Array(4).fill(' ').map((item, index) => ({ name: `${index + 1}季度`, value: index + 1 }));
            }
        });
        const handleSelectTongjiTypeChange = () => {
            selectMonthOrQuarter.value = 1;
            getRangeDate();
        };
        const selectMonthOrQuarter = ref<any>();
        const tableColumns = computed(() => {
            if (currIndex.value === 0) {
                if (tongjiType.value === '1') {
                    return [
                        {
                            title: '人员/使用时长(分钟)',
                            dataIndex: 'empName'
                        },
                        {
                            dataIndex: 'month1',
                            slots: { title: 'customMonthTitle1', customRender: 'month1' }
                        },
                        {
                            dataIndex: 'month2',
                            slots: { title: 'customMonthTitle2', customRender: 'month2' }
                        },
                        {
                            dataIndex: 'month3',
                            slots: { title: 'customMonthTitle3', customRender: 'month3' }
                        },
                        {
                            dataIndex: 'totalConsumingTime',
                            slots: { title: 'customTotalTitle' }
                        }
                    ];
                } else {
                    return [
                        {
                            title: '人员/使用时长(分钟)',
                            dataIndex: 'empName'
                        },
                        {
                            title: '1月',
                            dataIndex: 'month1'
                        },
                        {
                            title: '2月',
                            dataIndex: 'month2'
                        },
                        {
                            title: '3月',
                            dataIndex: 'month3'
                        },
                        {
                            title: '4月',
                            dataIndex: 'month4'
                        },
                        {
                            title: '5月',
                            dataIndex: 'month5'
                        },
                        {
                            title: '6月',
                            dataIndex: 'month6'
                        },
                        {
                            title: '7月',
                            dataIndex: 'month7'
                        },
                        {
                            title: '8月',
                            dataIndex: 'month8'
                        },
                        {
                            title: '9月',
                            dataIndex: 'month9'
                        },
                        {
                            title: '10月',
                            dataIndex: 'month10'
                        },
                        {
                            title: '11月',
                            dataIndex: 'month11'
                        },
                        {
                            title: '12月',
                            dataIndex: 'month12'
                        },
                        {
                            dataIndex: 'totalConsumingTime',
                            slots: { title: 'customTotalTitle' }
                        }
                    ];
                }
            } else {
                return [
                    {
                        title: '序号',
                        slots: { customRender: 'index' }
                    },
                    {
                        title: '人员',
                        dataIndex: 'empName'
                    },
                    {
                        title: '首次登录时间',
                        dataIndex: 'firstLoginTime'
                    }
                ];
            }
        });
        const getTotal = () => {
            api.userActionModel
                .getUserActions({
                    firstLogin: false,
                    pageNum: paginationConfig.value.current,
                    pageSize: paginationConfig.value.pageSize,
                    startTime: state.startTime,
                    endTime: state.endTime,
                    departmentId: state.departmentId,
                    teamId: state.teamId
                })
                .then((res) => {
                    if (res.success) {
                        huoyueTotal.value = res.totalCount;
                    }
                });
            api.userActionModel
                .getUserActions({
                    firstLogin: true,
                    pageNum: paginationConfig.value.current,
                    pageSize: paginationConfig.value.pageSize,
                    startTime: state.startTime,
                    endTime: state.endTime,
                    departmentId: state.departmentId,
                    teamId: state.teamId
                })
                .then((res) => {
                    if (res.success) {
                        addTotal.value = res.totalCount;
                    }
                });
        };
        const getList = async () => {
            setLoading(true);
            getTotal();
            const query = {
                firstLogin: currIndex.value === 0 ? false : true,
                pageNum: paginationConfig.value.current,
                pageSize: paginationConfig.value.pageSize,
                startTime: state.startTime,
                endTime: state.endTime,
                departmentId: state.departmentId,
                teamId: state.teamId
            };
            const { success, moule, totalCount } = await api.userActionModel.getUserActions(query);
            if (success) {
                list.value = moule.map((item, index) => {
                    const obj = {};
                    if (item.unitConsumingTime) {
                        Object.keys(item.unitConsumingTime).forEach((key: any) => {
                            if (key !== '0') {
                                obj[`month${key}`] = item.unitConsumingTime[key];
                            }
                        });
                    }
                    return {
                        ...item,
                        ...obj,
                        id: index
                    };
                });
                if (currIndex.value === 0) {
                    huoyueTotal.value = totalCount;
                } else {
                    addTotal.value = totalCount;
                }
                setPaginationConfig({
                    total: totalCount
                });
            }
            setLoading(false);
        };
        const getRangeDate = () => {
            if (tongjiType.value === '2') {
                state.startTime = moment(selectYear.value.toString()).startOf('year').format('YYYY-MM-DD HH:mm:ss');
                state.endTime = moment(selectYear.value.toString()).endOf('year').format('YYYY-MM-DD HH:mm:ss');
            } else {
                const val = selectMonthOrQuarter.value;
                state.startTime = moment(selectYear.value.toString()).quarter(val).startOf('quarter').format('YYYY-MM-DD HH:mm:ss');
                state.endTime = moment(selectYear.value.toString()).quarter(val).endOf('quarter').format('YYYY-MM-DD HH:mm:ss');
            }
            getList();
        };
        const handleSelectUserType = (index) => {
            currIndex.value = index;
            getList();
        };
        const handleCascaderChange = ({ nodeArr }) => {
            console.log('nodeArr', nodeArr);
            paginationConfig.value.current = 1;
            paginationConfig.value.pageSize = 20;
            if (nodeArr.length) {
                state.departmentId = nodeArr[0];
                if (nodeArr.length > 1) {
                    state.teamId = nodeArr[nodeArr.length - 1];
                } else {
                    const target = subTeamOptions.value.find((item) => item.id === state.departmentId);
                    if (target && target.subList) {
                        state.teamId = target.subList.map((item) => item.id).join(',');
                    } else {
                        state.teamId = target.id;
                    }
                }
            } else {
                state.teamId = '';
                state.departmentId = '';
            }
        };

        const getOrgTree = async () => {
            const { success, moule } = await api.portalControlModel.getOrganizationTree();
            if (success) {
                if (moule && moule.length) {
                    subTeamOptions.value = moule[0].subList[0].subList;
                }
            }
        };
        const handleTableChange = (val) => {
            paginationConfig.value = val;
            getList();
        };
        const exportFile = async () => {
            const query = {
                firstLogin: currIndex.value === 0 ? false : true,
                pageNum: paginationConfig.value.current,
                pageSize: paginationConfig.value.pageSize,
                startTime: state.startTime,
                endTime: state.endTime,
                departmentId: state.departmentId,
                teamId: state.teamId
            };
            const res = await api.userActionModel.userActionsDown(query, { responseType: 'blob' });
            res &&
                downByBlob(
                    res,
                    `${selectYear.value}年${tongjiType.value === '1' ? selectMonthOrQuarter.value + '季度' : ''}用户使用时长统计` + '.xls'
                );
        };
        // 初始化数据
        const init = () => {
            selectMonthOrQuarter.value = moment().quarter();
            getRangeDate();
            getOrgTree();
        };
        init();

        const handleSubmit = async () => {
            getList();
        };

        return {
            selectMonthOrQuarter,
            currIndex,
            handleSubmit,
            handleTableChange,
            exportFile,
            handleCascaderChange,
            timeOptions,
            handleSelectTongjiTypeChange,
            tableColumns,
            loading,
            handleSelectUserType,
            getRangeDate,
            paginationConfig,
            tongjiType,
            addTotal,
            huoyueTotal,
            ...toRefs(state),
            selectYear,
            subTeamOptions,
            list
        };
    }
});
</script>

<style scoped lang="less">
.active-1-bg {
    background-color: #fff7f2;
}
.active-1-text {
    color: #f7762a;
}
.active-2-bg {
    background-color: #e8ffeb;
}
.active-2-text {
    color: #01b88a;
}
.border {
    border: 1px solid #e9e9e9 !important;
}
.card-item {
    width: 306px;
    height: 98px;
    position: relative;
    cursor: pointer;
    border: 1px solid transparent;
}

.form-cont {
    ::v-deep(.ant-select-selector) {
        height: 31px !important;
    }
}
</style>